<template>
  <div class="wallet-page">
    <div class="header">
      <button class="back-button" @click="goBack"><i class="fas fa-arrow-left"></i> 返回</button>
      <h2>我的钱包</h2>
    </div>

    <div class="balance-section">
      <h3>当前余额</h3>
      <div class="balance-amount">¥ {{ balance }}</div>
    </div>

    <div class="recharge-section">
      <h3>充值</h3>
      <div class="recharge-input">
        <input
          type="number"
          v-model="rechargeAmount"
          placeholder="请输入充值金额"
          min="0"
          step="0.01"
        />
        <button @click="handleRecharge" :disabled="!rechargeAmount" class="recharge-button">
          充值
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { AxiosError } from 'axios'
import api from '@/utils/api'

const router = useRouter()
const route = useRoute()
const username = ref(route.query.username as string)
const balance = ref(0)
const rechargeAmount = ref('')

// 返回主页
const goBack = () => {
  router.back()
}

// 获取余额
const fetchBalance = async () => {
  console.log('开始获取余额，用户名:', username.value)
  try {
    const response = await api.get(`/api/users?username=${encodeURIComponent(username.value)}`)
    console.log('获取余额响应:', response.data)
    if (response.data) {
      // 从用户对象中提取余额字段
      balance.value = response.data.balance || 0
    }
  } catch (error) {
    const axiosError = error as AxiosError
    console.error('获取余额失败:', axiosError)
    if (axiosError.response) {
      console.error('错误状态码:', axiosError.response.status)
      console.error('错误响应数据:', axiosError.response.data)
      alert(`获取余额失败: ${axiosError.response.data || '服务器错误'}`)
    } else if (axiosError.request) {
      console.error('请求已发送但没有收到响应:', axiosError.request)
      alert('服务器无响应，请检查后端服务是否正常运行')
    } else {
      console.error('请求配置错误:', axiosError.config)
      alert('请求配置错误，请检查网络连接')
    }
  }
}

// 处理充值
const handleRecharge = async () => {
  if (!rechargeAmount.value || parseFloat(rechargeAmount.value) <= 0) {
    alert('请输入有效的充值金额')
    return
  }

  console.log('开始充值，用户名:', username.value, '金额:', rechargeAmount.value)
  try {
    const response = await api.post(`/api/users/${username.value}/recharge`, null, {
      params: {
        amount: rechargeAmount.value,
      },
    })
    console.log('充值响应:', response.data)
    alert(response.data)
    rechargeAmount.value = ''
    await fetchBalance() // 刷新余额
  } catch (error) {
    const axiosError = error as AxiosError
    console.error('充值失败:', axiosError)
    if (axiosError.response) {
      console.error('错误状态码:', axiosError.response.status)
      console.error('错误响应数据:', axiosError.response.data)
      alert(`充值失败: ${axiosError.response.data || '服务器错误'}`)
    } else if (axiosError.request) {
      console.error('请求已发送但没有收到响应:', axiosError.request)
      alert('服务器无响应，请检查后端服务是否正常运行')
    } else {
      console.error('请求配置错误:', axiosError.config)
      alert('请求配置错误，请检查网络连接')
    }
  }
}

onMounted(() => {
  console.log('钱包页面加载，用户名:', username.value)
  fetchBalance()
})
</script>

<style scoped>
.wallet-page {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 8px;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.back-button:hover {
  color: #333;
}

h2 {
  width: 100%;
  text-align: center;
  color: #2c3e50;
  margin: 0;
}

.balance-section {
  margin: 20px 0;
  padding: 30px;
  background-color: #f8f9fa;
  border-radius: 12px;
  text-align: center;
}

.balance-section h3 {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.balance-amount {
  font-size: 2.5em;
  color: #2c3e50;
  font-weight: bold;
  margin: 10px 0;
}

.recharge-section {
  margin: 20px 0;
  padding: 30px;
  background-color: #f8f9fa;
  border-radius: 12px;
}

.recharge-section h3 {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 18px;
}

.recharge-input {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

input {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #42b983;
}

.recharge-button {
  padding: 12px 30px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.recharge-button:hover:not(:disabled) {
  background-color: #3aa876;
}

.recharge-button:disabled {
  background-color: #a8d5c2;
  cursor: not-allowed;
}

@media (max-width: 480px) {
  .wallet-page {
    padding: 15px;
  }

  .balance-section,
  .recharge-section {
    padding: 20px;
  }

  .balance-amount {
    font-size: 2em;
  }
}
</style>
